package com.wgchao.authmanager.domain.model;

import com.wgchao.authmanager.domain.params.RoleUpdator;
import com.wgchao.authmanager.infrastructure.exception.ObjectDisabledException;
import lombok.Getter;

import java.util.Date;

/**
 * @ClassName: Role
 * @author: wgchao
 * @createTime: 2020/4/26 11:06 AM
 * @Description: 角色
 */
@Getter
public class Role extends DomainIdentify {
    //全局标识
    private RoleIdentity identity;

    private String remark;

    private boolean disabled;

    private Operator creator;

    private Operator lastupdator;

    protected Role(RoleIdentity identity, String remark, boolean disabled, Operator creator, Operator lastupdator) {
        this.identity = identity;
        this.remark = remark;
        this.disabled = disabled;
        this.creator = creator;
        this.lastupdator = lastupdator;
    }

    public Role(Long id, RoleIdentity identity, String remark,
                   boolean disabled, Operator creator, Operator lastupdator, Long version) {
        setId(id);
        this.identity = identity;
        this.remark = remark;
        this.disabled = disabled;
        this.creator = creator;
        this.lastupdator = lastupdator;
        setVersion(version);
    }

    public String getRoleName(){
        return this.identity.getRoleName();
    }
    public String getAgencyCode(){
        return this.identity.getAgencyCode();
    }

    public static Role addRole(Agency agency, String roleName, String remark, String operator){
        if(!agency.normal()){
            throw new ObjectDisabledException("所在机构不可用");
        }

        return new Role(new RoleIdentity(agency.getAgencyCode(), roleName), remark,
                false, new Operator(operator, new Date()), null);
    }

    public boolean normal(){
        return !this.disabled;
    }

    public void resiveInfo(RoleUpdator updator, String operator){
        if(!normal()){
            throw new ObjectDisabledException("角色不可用");
        }
        if(updator.getRemark() != null){
            this.remark = updator.getRemark().orElse(null);
        }
        this.lastupdator = new Operator(operator, new Date());
    }

    public void stopUsing(String operator) {
        this.disabled = true;
        this.lastupdator = new Operator(operator, new Date());
    }

    public void reEnable(String operator) {
        this.disabled = false;
        this.lastupdator = new Operator(operator, new Date());
    }

    public void assertBelongTo(Agency agency){
        identity.assertBelongTo(agency);
    }
}
